package pk.nak.client.activity;

import com.google.android.maps.GeoPoint;

import pk.nak.adapters.EatOutAdapter;
import pk.nak.client.R;
import pk.nak.data.EatOut;
import pk.nak.enums.AppVars;
import pk.nak.enums.ExtraIDs;
import pk.nak.overlays.EatOutOverlayItem;
import pk.nak.requests.GetLocationsRequest;
import pk.nak.requests.NearestEatOutsRequest;
import pk.nak.responses.GetLocationsResponse;
import pk.nak.responses.NearestEatOutsResponse;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

public class NearestEatoutActivity extends Activity {
	
	private boolean firstTime = true;
	GetLocationsResponse glresponse = new GetLocationsResponse(){

		@Override
		public void onSuccess(String response) {
			// TODO Auto-generated method stub
			super.onSuccess(response);
			Spinner sp = (Spinner) findViewById(R.id.spEatoutLocs);
			if ( sp != null ){
				this.Overlays().add(0, new EatOutOverlayItem(new GeoPoint((int)(AppVars.device_lat * 1e6),(int)(AppVars.device_lng*1e6)), "", "My Location"));
				ArrayAdapter<EatOutOverlayItem> aaItems = new ArrayAdapter<EatOutOverlayItem>(getApplicationContext(), android.R.layout.simple_spinner_item,this.Overlays());
				sp.setAdapter(aaItems);
			}
		}
		
	};
	
	NearestEatOutsResponse neorp = new NearestEatOutsResponse(){

		@Override
		public void onSuccess(String response) {
			// TODO Auto-generated method stub
			super.onSuccess(response);
			AppVars.pdWait.dismiss();
			AppVars.EatOuts = this.getEatouts();
			
			ListView lv = (ListView)findViewById(R.id.lvEatouts);
			EatOutAdapter aaEatOut = new EatOutAdapter(getApplicationContext(), R.layout.eatoutrow,AppVars.EatOuts.getEatOuts());
			
			if ( lv != null ){
				lv.setAdapter(aaEatOut);
			}else{
				Toast.makeText(getApplicationContext(), "LV is null", Toast.LENGTH_SHORT).show();
			}
			
		}
		
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.nearesteatout);
	    //this.PopulateEatOuts();
	    
	    this.AttachedHandlers();
	    this.GetDeviceLocation();

	    NearestEatOutsRequest neorq = new NearestEatOutsRequest(AppVars.device_lat,AppVars.device_lng);
	    neorq.doRequst(neorp);
	    
	    GetLocationsRequest glreq = new GetLocationsRequest(AppVars.LogedInUserID);
	    glreq.doRequest(glresponse);
	    
	    AppVars.pdWait = ProgressDialog.show(this, "Loading EatOuts", "Loading");
	}
	
	private void GetDeviceLocation(){
		try{
			LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
		    boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);

		    // Check if enabled and if not send user to the GSP settings
		    // Better solution would be to display a dialog and suggesting to 
		    // go to the settings
		    if (!enabled) {
		    	
		    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
		    	builder.setMessage("GPS is not enabled, do you want to enable GPS settings?")
		    	       .setCancelable(false)
		    	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		    	           public void onClick(DialogInterface dialog, int id) {
		    	                //MeetingMap.this.finish();
		    	     	      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		    	     	      startActivity(intent);
		    	           }
		    	       })
		    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		    	           public void onClick(DialogInterface dialog, int id) {
		    	                dialog.cancel();
		    	           }
		    	       });
		    	builder.create();
		    }
		    
		    // Get current location coordinates
		    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		    Criteria criteria = new Criteria();
		    criteria.setAccuracy(Criteria.ACCURACY_FINE);
		    criteria.setAltitudeRequired(false);
		    String best = locationManager.getBestProvider(criteria, true);
		    LocationProvider lp = locationManager.getProvider(best);
		    
		    if ( lp == null ){
		    	Toast.makeText(this, "GPS Location provider is not available at this time.",Toast.LENGTH_LONG).show();
		    }else{
			    Location lastKnownLocation = locationManager.getLastKnownLocation(best);

			    if ( lastKnownLocation != null ){
			    	AppVars.device_lat = lastKnownLocation.getLatitude();
			    	AppVars.device_lng = lastKnownLocation.getLongitude();
			    	
			    	Toast.makeText(this, "Current Lat/Lng: " + (int) (AppVars.device_lat) + ", "+ (int) (AppVars.device_lng),Toast.LENGTH_LONG).show();
			    }else{
			    	Toast.makeText(this, "Last known location is not available",Toast.LENGTH_LONG).show();
			    }
		    }
		}catch(Exception ex){
		
		}
	}
	
	private void AttachedHandlers(){
		ListView lv = (ListView)findViewById(R.id.lvEatouts);
		if ( lv != null ){
			lv.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
					
					// TODO Auto-generated method stub
					final EatOut selectedEO = (EatOut)parent.getItemAtPosition(position);
					Intent detailsWindow = new Intent(view.getContext(),EatOutDetailsActivity.class);
					detailsWindow.putExtra(ExtraIDs.SELECTED_EATOUT_SERIALIZABLE, selectedEO);
					startActivity(detailsWindow);
					Toast.makeText(view.getContext(), selectedEO.getEatoutName(), Toast.LENGTH_SHORT).show();
					
				}
				
			});
		}		

		Spinner sp = (Spinner) findViewById(R.id.spEatoutLocs);
		if ( sp != null ){
			sp.setOnItemSelectedListener(new OnItemSelectedListener() {

				public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
					if ( firstTime ) {
						firstTime = false;
						return;
					}
					// TODO Auto-generated method stub
					Spinner sp = (Spinner) findViewById(R.id.spEatoutLocs);
					EatOutOverlayItem eooi = (EatOutOverlayItem) sp.getSelectedItem();
					Toast.makeText(getApplicationContext(), eooi.getSnippet(), Toast.LENGTH_SHORT).show();
					double lat = eooi.getPoint().getLatitudeE6() / 1e6;
					double lng = eooi.getPoint().getLongitudeE6() / 1e6;
					NearestEatOutsRequest neorq = new NearestEatOutsRequest(lat,lng);
				    neorq.doRequst(neorp);
				    
				    //AppVars.pdWait = ProgressDialog.show(v.getContext(), "Loading EatOuts", "Loading");
				}

				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
				
			});			
		}
	}
}
